import { ref, reactive } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import toast from "@/utils/Toast";

export default function pageQueryService() {
  return {
    setup(beans, pageQuery, total, listLength) {
      const params = reactive({
        limit: 15,
        start: 0,
      });
      const isFetching = ref(false);
      const fetchTimeout = ref(null);

      onReachBottom(() => {
        if (listLength.value === total.value) return;
        if (isFetching.value) return;
        isFetching.value = true;
        if (fetchTimeout.value) clearTimeout(fetchTimeout.value);
        toast.info("加载中...");
        fetchTimeout.value = setTimeout(() => {
          params.start += params.limit;
          pageQuery();
        }, 500);
      });

      const initParams = () => {
        Object.assign(params, {
          limit: 15,
          start: 0,
        });
        isFetching.value = false;
        if (beans && beans.list) {
          beans.list.length = 0;
        }
        pageQuery();
      };

      return {
        params,
        initParams,
      };
    },
  };
}
